package com.jlnk.stockdemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jlnk.stockdemo.R;
import com.jlnk.stockdemo.activity.StockActivity;
import com.jlnk.stockdemo.adapter.StockAdapter;
import com.jlnk.stockdemo.bean.StockListResponse;
import com.jlnk.stockdemo.viewmodel.StockViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class StockFragment extends Fragment {
    private static final String TAG = "StockFragment";
    private StockViewModel stockViewModel;
    private RecyclerView recyclerview_stock;
    private StockAdapter stockAdapter;
    private List<StockListResponse.Data.Stock> stockList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_stock, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        stockAdapter = new StockAdapter(stockList);
        stockAdapter.setOnItemClickListener(new StockAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(StockListResponse.Data.Stock stockItem) {
                Intent intent = new Intent(getActivity(), StockActivity.class);
                intent.putExtra("ts_code", stockItem.getTsCode());
                intent.putExtra("symbol", stockItem.getSymbol());
                intent.putExtra("name", stockItem.getName());
                intent.putExtra("area", stockItem.getArea());
                intent.putExtra("industry", stockItem.getIndustry());
                intent.putExtra("market", stockItem.getMarket());
                startActivity(intent);
            }
        });

        recyclerview_stock = view.findViewById(R.id.recyclerview_stock);
        recyclerview_stock.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerview_stock.setAdapter(stockAdapter);

        stockViewModel = new ViewModelProvider(this).get(StockViewModel.class);
        stockViewModel.getStockListLiveData().observe(getViewLifecycleOwner(), stocks -> {
            Log.d(TAG, "stockList: " + stocks.size());
            this.stockList.clear();
            this.stockList.addAll(stocks);
            stockAdapter.notifyDataSetChanged();
        });
        stockViewModel.fetchStockList();
    }
}
